﻿using EFCore.Dbfirst.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MSACommerce.Interface;
using MSACommerce.Service;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace MSACommerce.UserMicroservice.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    //[Microsoft.AspNetCore.Authorization.Authorize]  //授权
    public class UsersController : ControllerBase
    {
        private readonly ILogger<UsersController> _logger;
        private readonly IConfiguration _iConfiguration;
        public virtual IUserService _userService { get; set; }

        public UsersController(ILogger<UsersController> logger, IConfiguration iConfiguration, IUserService userService)
        {
            _logger = logger;
            _iConfiguration = iConfiguration;
            _userService = userService;
        }

        [HttpGet]
        [Route("Index")]//拼接到控制器上的route
        public JsonResult Index()
        {
            this._logger.LogWarning($"This is HealthController {this._iConfiguration["Port"]}");
            //获取登陆信息
            foreach (var item in base.HttpContext.User.Identities.First().Claims)
            {
                Console.WriteLine($"{item.Type}:{item.Value}");
            }

            IEnumerable<Claim> claims = HttpContext.AuthenticateAsync().Result.Principal.Claims;
            if (claims != null && claims.Count() > 0)
            {
                string name = claims.FirstOrDefault(u => u.Type == "Account").Value;
                string Name = claims.FirstOrDefault(u => u.Type == "Name").Value;
                return new JsonResult(Name);
            }

            return new JsonResult("");//HttpStatusCode--200
        }

        [HttpPost]
        [Route("AddUser")]
        [Authorize(Roles = "Admin")]
        public IActionResult AddUser(Users account)

        {
            _userService.AddUser(account);
            return Ok(new { state = "success", message = "添加成功" });
        }
    }
}